/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class DomUtils {

    public static Node buildDomTree(String nameSpace, String rootName, String elementsName, Map<String, Object> properties) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder loader = factory.newDocumentBuilder();
            Document document = loader.newDocument();
            // here is our vendor URL used in namepace-related functions:
            String docNS = nameSpace;

            // create document element:
            Element root = document.createElementNS(docNS, rootName);
            document.appendChild(root);
            Element res = document.createElementNS(docNS, elementsName);
            Set<String> keys = properties.keySet();
            for (String key : keys) {
                Element ele = document.createElementNS(docNS, key);
                ele.setTextContent(properties.get(key).toString());
                res.appendChild(ele);
            }
            root.appendChild(res);
            return document;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(DomUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
